package com.fourforfo.fourmall.seckill.controller;

import com.fourforfo.common.utils.R;
import com.fourforfo.fourmall.seckill.service.SeckillService;
import com.fourforfo.fourmall.seckill.to.SeckillSessionWithSkusTO;
import com.fourforfo.fourmall.seckill.to.SeckillSkuRedisTO;
import com.xxl.sso.core.conf.Conf;
import com.xxl.sso.core.user.XxlSsoUser;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @program: xxl-sso-core
 * @description:
 * @author: fourforfo
 * @email: fourforfo@gmail.com
 * @create: 2022-09-15 13:05
 **/
@Controller
public class SeckillController {



    @Autowired
    SeckillService seckillService;

    /**
     * 获取当前参与秒杀的商品信息
     * @return
     */
    @ResponseBody
    @GetMapping("/currentSeckillSkus")
    public R getCurrentSeckillSkus(){

        List<SeckillSkuRedisTO> vos = seckillService.getCurrentSeckillSkus();

        return R.ok().setData(vos);
    }

    /**
     * 获取某商品的秒杀信息，即是否是秒杀商品，以及秒杀的上次等等
     */
    @ResponseBody
    @GetMapping("/sku/seckill/{skuId}")
    public R getSkuSeckillInfo(@PathVariable("skuId")Long skuId){
        if(skuId==null||skuId==0l){
            return R.error("参数错误");
        }

        SeckillSkuRedisTO to = seckillService.getSkuSeckillInfo(skuId);

        return R.ok().setData(to);

    }

    /**
     * 秒杀服务请求处理
     * @return
     */
    @GetMapping("/seckill")
    public String secKill(@RequestParam("killId")String killId,
                          @RequestParam("key")String randomCode,
                          @RequestParam("num")Integer num,
                          HttpServletRequest request,
                          Model model){
        if(killId==null || randomCode==null || num==null || num==0){
            model.addAttribute("errorMsg","请求参数异常！");
            return "success";
        }
        //通过配置文件动态指定限购数量maxNum的值
        if(num>=3){
            model.addAttribute("errorMsg","超出限购数量，每人限购两件！");
            return "success";
        }

        XxlSsoUser xxlUser = (XxlSsoUser) request.getAttribute(Conf.SSO_USER);
        if(xxlUser==null){
            model.addAttribute("errorMsg","用户登录状态异常！");
            return "success";
        }


        R r = seckillService.seckill(killId,randomCode,num,xxlUser.getUserid());
        if(r.getCode()==0){
            model.addAttribute("successMsg",r.getMsg());
        }else{
            model.addAttribute("errorMsg",r.getMsg());
        }

        return "success";
    }
}
